<!-- 编辑 -->
<template>
  <PageMain>
    <pageBack />
    <div class="pl-24px pr-24px">
      <el-form ref="formRef" :model="formData" :rules="rules" label-position="top" size="default">
        <div class="brw pt-12px">
          <div class="use-title-icon">基础信息</div>
          <!-- 个人 -->
          <el-row gutter="90" v-if="formData.type === 'PERSON'">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactName">
                <el-input v-model="formData.contactName" placeholder="请输入联系人" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model.number="formData.phone" disabled placeholder="请输入联系电话" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 企业 -->
          <el-row gutter="90" v-if="formData.type === 'COMPANY'">
            <el-col>
              <el-form-item label="企业图片" prop="companyImg">
                <avatarUpload v-model="formData.companyImg" accept=".png,.jpg,.jpeg" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业名称" prop="companyName">
                <el-input v-model="formData.companyName" placeholder="请输入企业名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业规模" prop="companyScale">
                <el-radio-group v-model="formData.companyScale">
                  <el-radio :value="1">0-50人</el-radio>
                  <el-radio :value="2">51-200人</el-radio>
                  <el-radio :value="3">200人以上</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业类型" prop="categoryCodes">
                <el-checkbox-group v-model="formData.categoryCodes">
                  <el-checkbox
                    v-for="(item, index) in categoryList"
                    :key="index"
                    :label="item.categoryName"
                    :value="item.categoryCode"
                  />
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactName">
                <el-input v-model="formData.contactName" placeholder="请输入联系人" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="cantactPhone">
                <el-input v-model.number="formData.cantactPhone" disabled placeholder="请输入联系电话" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="地址" prop="address">
                <el-input
                  v-model="formData.address"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  placeholder="请输入地址"
                  show-word-limit
                  :maxlength="300"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="企业详情" prop="companyDesc">
                <el-input
                  v-model="formData.companyDesc"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  placeholder="请输入企业详情"
                  show-word-limit
                  :maxlength="300"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <template v-if="formData.type === 'COMPANY'">
          <div class="brw pt-12px mt-12px" v-if="formData.categoryCodes.includes('OVERSEAS_WAREHOUSE')">
            <div class="use-title-icon">海外仓</div>
            <el-row gutter="90">
              <el-col :span="12" v-for="(item, index) in serviceData[0]?.child" :key="index">
                <el-form-item
                  v-if="formData.userCompanyServiceObj['OVERSEAS_WAREHOUSE'].serviceItemTypeVO[index]"
                  :label="item.name"
                  :prop="'userCompanyServiceObj.OVERSEAS_WAREHOUSE.serviceItemTypeVO.' + index + '.serviceItemList'"
                  :rules="{
                    type: 'array',
                    required: true,
                    message: '必填项不能为空',
                    trigger: 'change',
                  }"
                >
                  <el-checkbox-group
                    v-model="formData.userCompanyServiceObj['OVERSEAS_WAREHOUSE'].serviceItemTypeVO[index].serviceItemList"
                  >
                    <el-checkbox v-for="(it, idx) in item.child" :key="idx" :label="it.name" :value="it.code" />
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="海外仓" prop="companyWarehouseList">
                  <div class="warehouseListBtn" @click="warehouseListPush">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    添加海外仓
                  </div>

                  <ProTable
                    ref="tableRef"
                    class="tableRef"
                    :columns="columns"
                    :data="formData.companyWarehouseList"
                    :border="true"
                    :requestAuto="false"
                    :pagination="false"
                  >
                  </ProTable>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="brw pt-12px mt-12px" v-if="formData.categoryCodes.includes('SPECIAL_LINE')">
            <div class="use-title-icon">专线</div>
            <el-row gutter="90">
              <el-col :span="12" v-for="(item, index) in serviceData[1]?.child" :key="index">
                <el-form-item
                  v-if="formData.userCompanyServiceObj['SPECIAL_LINE'].serviceItemTypeVO[index]"
                  :label="item.name"
                  :prop="'userCompanyServiceObj.SPECIAL_LINE.serviceItemTypeVO.' + index + '.serviceItemList'"
                  :rules="{
                    type: 'array',
                    required: true,
                    message: '必填项不能为空',
                    trigger: 'change',
                  }"
                >
                  <el-checkbox-group
                    v-model="formData.userCompanyServiceObj['SPECIAL_LINE'].serviceItemTypeVO[index].serviceItemList"
                  >
                    <el-checkbox v-for="(it, idx) in item.child" :key="idx" :label="it.name" :value="it.code" />
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col class="pt-10px pb-10px"><strong>专线服务</strong></el-col>
              <el-col :span="12">
                <el-form-item label="包裹限重" prop="packageWeightMin">
                  <div class="flex">
                    <el-input v-model.number="formData.packageWeightMin" placeholder="请输入最小重量">
                      <template #append>kg</template>
                    </el-input>
                    <span class="pl-8px pr-8px color-#999"> - </span>
                    <el-input v-model.number="formData.packageWeightMax" placeholder="请输入最大重量">
                      <template #append>kg</template>
                    </el-input>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="尺寸限制" prop="packageLength">
                  <div class="flex">
                    <el-input v-model.number="formData.packageLength" placeholder="长">
                      <template #append>cm</template>
                    </el-input>
                    <span class="pl-8px pr-8px color-#999"> - </span>
                    <el-input v-model.number="formData.packageWidth" placeholder="宽">
                      <template #append>cm</template>
                    </el-input>
                    <span class="pl-8px pr-8px color-#999"> - </span>
                    <el-input v-model.number="formData.packageHeight" placeholder="高">
                      <template #append>cm</template>
                    </el-input>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="送货地区" prop="deliveryCityCodes">
                  <el-checkbox-group v-model="formData.deliveryCityCodes">
                    <el-checkbox v-for="(item, index) in cityList" :key="index" :label="item.nameCn" :value="item.code" />
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="申报要求" prop="declareDesc">
                  <el-input
                    v-model="formData.declareDesc"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请输入申报要求"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="brw pt-12px mt-12px" v-if="formData.categoryCodes.includes('SERVICE_PROVIDER')">
            <div class="use-title-icon">服务商</div>
            <el-row gutter="90">
              <el-col :span="12" v-for="(item, index) in serviceData[2]?.child" :key="index">
                <el-form-item
                  v-if="formData.userCompanyServiceObj['SERVICE_PROVIDER'].serviceItemTypeVO[index]"
                  :label="item.name"
                  :prop="'userCompanyServiceObj.SERVICE_PROVIDER.serviceItemTypeVO.' + index + '.serviceItemList'"
                  :rules="{
                    type: 'array',
                    required: true,
                    message: '必填项不能为空',
                    trigger: 'change',
                  }"
                >
                  <el-checkbox-group
                    v-model="formData.userCompanyServiceObj['SERVICE_PROVIDER'].serviceItemTypeVO[index].serviceItemList"
                  >
                    <el-checkbox v-for="(it, idx) in item.child" :key="idx" :label="it.name" :value="it.code" />
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </template>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">修改确认</el-button>
        </el-form-item>
      </el-form>
    </div>
  </PageMain>
</template>
<script lang="jsx" setup>
import api from "@/api";
const router = useRouter();
const route = useRoute();
const packageWeighValid = (rule, value, callback) => {
  if (value == "" || value == undefined) {
    callback(new Error("请输入最小重量"));
  } else if (formData.value.packageWeightMax === "" || formData.value.packageWeightMax === undefined) {
    callback(new Error("请输入最大重量"));
  } else {
    callback();
  }
};
const packageSizeValid = (rule, value, callback) => {
  if (formData.value.packageLength || formData.value.packageWidth || formData.value.packageHeight) {
    if (!formData.value.packageLength) {
      callback(new Error("请输入长度"));
    } else if (!formData.value.packageWidth) {
      callback(new Error("请输入宽度"));
    } else if (!formData.value.packageHeight) {
      callback(new Error("请输入高度"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const rules = {
  companyImg: [{ required: true, message: "请上传图片", trigger: "blur" }],
  companyName: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  companyScale: [{ required: true, message: "选择企业规模", trigger: "change" }],
  categoryCodes: [{ type: "array", required: true, message: "选择企业类型", trigger: "change" }],
  contactName: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  companyDesc: [{ required: true, message: "请输入企业详情", trigger: "blur" }],
  packageWeightMin: [{ required: true, validator: packageWeighValid, trigger: "blur" }],
  deliveryCityCodes: [{ required: true, message: "请选择送货地区", trigger: "blur" }],
  declareDesc: [{ required: true, message: "请输入申报要求", trigger: "blur" }],
  packageLength: [{ validator: packageSizeValid, trigger: "blur" }],
  address: [{ required: true, message: "请输入地址", trigger: "blur" }],
  // companyWarehouseList: [{ type: "array", required: true, message: "请添加海外仓", trigger: "change" }],
};

const formData = ref({
  type: "PERSON",
  companyWarehouseList: [],
  userCompanyServiceObj: {},
});

// 表格配置项
const columns = [
  {
    label: "图片",
    prop: "warehouseImg",
    align: "left",
    width: "100px",
    headerRender: ({ column }) => {
      return <div class="headerLabel">{column.label}</div>;
    },
    render: ({ row, column, $index }) => {
      return (
        <el-form-item
          prop={"companyWarehouseList." + $index + "." + column.property}
          rules={{ required: true, message: "必填项不能为空", trigger: "blur" }}
        >
          <avatarUpload class="avatarUpload" vModel={row[column.property]} accept=".png,.jpg,.jpeg" />
        </el-form-item>
      );
    },
  },
  {
    label: "名称",
    prop: "warehouseName",
    align: "left",
    headerRender: ({ column }) => {
      return <div class="headerLabel">{column.label}</div>;
    },
    render: ({ row, column, $index }) => {
      return (
        <el-form-item
          prop={"companyWarehouseList." + $index + "." + column.property}
          rules={{ required: true, message: "必填项不能为空", trigger: "blur" }}
        >
          <el-input vModel={row[column.property]} placeholder="请输入名称" clearable></el-input>
        </el-form-item>
      );
    },
  },
  {
    label: "面积",
    prop: "warehouseArea",
    align: "left",
    headerRender: ({ column }) => {
      return <div class="headerLabel">{column.label}</div>;
    },
    render: ({ row, column, $index }) => {
      return (
        <el-form-item
          prop={"companyWarehouseList." + $index + "." + column.property}
          rules={{ required: true, message: "必填项不能为空", trigger: "blur" }}
        >
          <el-input vModel={row[column.property]} placeholder="请输入面积" clearable></el-input>
        </el-form-item>
      );
    },
  },
  {
    label: "地址",
    prop: "warehouseAddress",
    align: "left",
    headerRender: ({ column }) => {
      return <div class="headerLabel">{column.label}</div>;
    },
    render: ({ row, column, $index }) => {
      return (
        <el-form-item
          prop={"companyWarehouseList." + $index + "." + column.property}
          rules={{ required: true, message: "必填项不能为空", trigger: "blur" }}
        >
          <el-input vModel={row[column.property]} placeholder="请输入地址" clearable></el-input>
        </el-form-item>
      );
    },
  },
  {
    prop: "operation",
    label: "操作",
    align: "center",
    fixed: "right",
    width: 200,
    render: ({ row, column, $index }) => {
      return (
        <el-button
          type="warning"
          link
          disabled={formData.value.companyWarehouseList.length === 1}
          onClick={() => warehouseListReduce($index)}
        >
          删除
        </el-button>
      );
    },
  },
];

// 增加仓库
const warehouseListPush = () => {
  formData.value.companyWarehouseList.push({});
};
// 减少仓库
const warehouseListReduce = (index) => {
  formData.value.companyWarehouseList.splice(index, 1);
};

const formRef = ref();
const onSubmit = () => {
  formRef.value.validate((valid, obj) => {
    if (valid) {
      const userCompanyServiceList = [];
      if (formData.value.type === "COMPANY") {
        Object.keys(formData.value.userCompanyServiceObj).forEach((key) => {
          const item = formData.value.userCompanyServiceObj[key]
          if (formData.value.categoryCodes.includes(item.categoryCode)) {
            const data = [];
            item.serviceItemTypeVO.forEach((it) => {
              it.serviceItemList = it.serviceItemList.map((d) => {
                return {
                  code: d,
                };
              });
              data.push({
                categoryCode: item.categoryCode,
                serviceItemTypeVO: it,
              });
            });
            userCompanyServiceList.push(...data);
          }
        });
      }
      let url = formData.value.type === "COMPANY" ? "/user/update/company" : "/user/update/person";
      api
        .post(
          url,
          {
            ...formData.value,
            deliveryCityCodes: formData.value.deliveryCityCodes?.join(","),
            categoryCodes: formData.value.categoryCodes?.join(","),
            userCompanyServiceList,
          },
          { msg: true, loading: true }
        )
        .then((res) => {
          router.back();
        });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

// 获取详情
const getDelail = async () => {
  await api.get(`/user/detail/${route.query.id}`).then(async (res) => {
    // 公司 需要获更多数据
    if (res.type === "COMPANY") {
      getCategory();
      Object.assign(formData.value, res.userCompanyDetailVO);
      formData.value.type = "COMPANY";
      if (formData.value.deliveryCityCodes) {
        formData.value.deliveryCityCodes = formData.value.deliveryCityCodes.split(",");
      } else {
        formData.value.deliveryCityCodes = [];
      }
      if (formData.value.categoryCodes) {
        formData.value.categoryCodes = formData.value.categoryCodes.split(",");
      } else {
        formData.value.categoryCodes = [];
      }
      formData.value.userCompanyServiceObj = companyServiceListSet(res.userCompanyDetailVO.companyServiceList);
    } else {
      Object.assign(formData.value, res);
    }
  });
};
// 将接口数据转为可用结构
const companyServiceListSet = (metadata) => {
  const list = JSON.parse(JSON.stringify(metadata));
  const staging = {};
  for (let index = 0; index < list.length; index++) {
    const item = list[index];
    const serviceItemTypeVO = {
      name: item.serviceItemTypeVO.name,
      code: item.serviceItemTypeVO.code,
      serviceItemList: item.serviceItemTypeVO.serviceItemList.map((it) => it.code),
    };
    if (!staging[item.categoryCode]) {
      staging[item.categoryCode] = {
        categoryCode: item.categoryCode,
        categoryName: item.categoryName,
        serviceItemTypeVO: [serviceItemTypeVO],
      };
    } else {
      staging[item.categoryCode].serviceItemTypeVO.push(serviceItemTypeVO);
    }
  }
  return staging;
};

// 根据平台配置 生成数据结构
const serviceData = ref([]);
const categoryList = ref();
const getCategory = () => {
  serviceData.value = [];
  api.post(`/serviceCategory/queryList`).then(async (res) => {
    categoryList.value = res;
    for (let index = 0; index < res.length; index++) {
      const item = res[index];
      const data = await getServiceData({ categoryId: res[index].id, parentId: 0 });
      if (!formData.value.userCompanyServiceObj[item.categoryCode]) {
        formData.value.userCompanyServiceObj[item.categoryCode] = {
          categoryCode: item.categoryCode,
          serviceItemTypeVO: JSON.parse(JSON.stringify(data)).map((it) => {
            return {
              code: it.code,
              serviceItemList: [],
              name: it.name,
            };
          }),
        };
      }
      for (let j = 0; j < data.length; j++) {
        const itemj = data[j];
        const childData = await getServiceData({ categoryId: itemj.categoryId, parentId: itemj.id });
        data[j].child = childData.map((it) => {
          return {
            code: it.code,
            name: it.name,
          };
        });
      }
      item.child = data;
      serviceData.value.push(item);
    }
    console.log("userCompanyServiceObj:", formData.value.userCompanyServiceObj);
  });
};

const getServiceData = (params) => {
  return new Promise((resolve, reject) => {
    api.post(`/serviceItem/queryList`, params).then((res) => {
      resolve(res);
    });
  });
};

// 送货地区
const cityList = ref();
const getCityList = () => {
  api.post("/city/queryList", { keyword: "" }).then((res) => {
    cityList.value = res;
  });
};
onMounted(async () => {
  await getDelail();
  getCityList();
});
</script>
<style scoped lang="scss">
::v-deep(.avatarUpload) {
  .avatar {
    width: 70px;
    height: 70px;
  }

  .el-icon.avatar-uploader-icon {
    width: 70px;
    height: 70px;
  }
}

.warehouseListBtn {
  width: 100%;
  height: 32px;
  line-height: 32px;
  border: 1px solid var(--use-color-warning);
  border-radius: 4px;
  color: var(--use-color-warning);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

::v-deep(.headerLabel) {
  &::before {
    content: "*";
    color: var(--el-color-danger);
    margin-right: 4px;
  }
}

::v-deep(.table-main) {
  padding: 0 !important;
  margin-top: 0;
  width: 100%;
}
</style>
